var selectedFeature = null;

$(document).ready(function() {
    var types = null;
    $.ajax({
        url: "vote_types.json",
        dataType: "json",
        context: this,
        success: function(data, textStatus, jqXHR){
            types = data.types;
        }
    });

    // Start with the map page
    if (window.location.hash && window.location.hash!='#mappage') {
        $.mobile.changePage('mappage');
    }

    // fix height of content
    function fixContentHeight() {
        var footer = $("div[data-role='footer']:visible"),
        content = $("div[data-role='content']:visible:visible"),
        viewHeight = $(window).height(),
        contentHeight = viewHeight - footer.outerHeight();

        if ((content.outerHeight() + footer.outerHeight()) !== viewHeight) {
            contentHeight -= (content.outerHeight() - content.height());
            content.height(contentHeight);
        }
        if (window.map) {
            map.updateSize();
        } else {
            // initialize map
            init(function(feature) { 
                selectedFeature = feature; 
                $.mobile.changePage($("#popup"), "pop"); 
            });
        }
    }
    $(window).bind("orientationchange resize pageshow", fixContentHeight);
    fixContentHeight(); 
    //init();

    // Map zoom  
    $("#plus").click(function(){
        map.zoomIn();
    });
    $("#minus").click(function(){
        map.zoomOut();
    });
    $("#locate").click(function(){
        var control = map.getControlsBy("id", "locate-control")[0];
        if (control.active) {
            control.getCurrentLocation();
        } else {
            control.activate();
        }
    });


    // IMPORTANT NOTE about STYLE attribute below
    // Need that -- can't use CSS to do this reliably (at least I couldn't) get CSS to work properly -- see .opt-left & .opt-right in style.mobile.css
    // Also, 25% / 75% is proper spacing on smaller screens for the left side content
    //  
    $('div#popup').live('pageshow',function(event, ui){
        var li = "";
        for(var attr in selectedFeature.attributes){
            li += '<li>'
               +  '<div style="width:25%;float:left">'  + attr + '</div>'
               +  '<div style="width:75%;float:right">' + selectedFeature.attributes[attr] + '</div>'
               +  '</li>'; 
        }

        var vote_id = "vote-";
        var tot_id  = "total-";
        var desc_id = "description-";

        if(types)
        for(var i=0; i < types.length; i++)
        {
            // only show vote types that are turned on...
            if(types[i].display != "1")
                continue; 

            var vid = vote_id + types[i].id;
            var did = desc_id + types[i].id;
            var tot = tot_id  + types[i].id;

            li += '<li>'
               +  '<div style="width:25%;float:left" title="' + types[i].description + '">'  + types[i].name + '<div id="' + tot + '" class="total">No votes yet</div></div>'
               +  '<div style="width:75%;float:right">' + '<div id="' + vid + '" class="left" vote_type="' + types[i].id + '"></div><div id="' + did + '" class="raty-target"></div></div>';
               +  '<li>';
        }

        $("ul#details-list").empty().append(li).listview("refresh");

        // create votes with null averages
        if(types)
        for(var i=0; i < types.length; i++) 
        {
            // only show vote types that are turned on...
            if(types[i].display != "1")
                continue; 

            var vid = '#' + vote_id + types[i].id;
            var did = '#' + desc_id + types[i].id;
            var hints = [types[i].value_1, types[i].value_2, types[i].value_3, types[i].value_4, types[i].value_5];

            $(vid).raty({
                cancel: true,
                path: '../images/ui/vote',
                start: null,
                cancelHint: 'none',
                hintList: hints,
                target: did,
                vote_type: types[i].id,
                click: function(score, evt){
                    var c = confirm("Submit your vote of " + score + " stars?");
                    if(c == true)
                    {
                        var vt = this.selector.substring(this.selector.length-1); 
                        var url = 'vote.json?feature=X&type=' + vt + '&vote=' + score;
                        $.ajax({
                            url: url,
                            dataType: "json",
                            context: this,
                            success: function(data, textStatus, jqXHR){
                                alert("OK");
                            }
                        });
                    }
                }
            });
        }

        // make call to service to get actual votes
        var cfg = {
            url: "vote.json",
            dataType: "json",
            context: this,
            success: function(data, textStatus, jqXHR, x, y){
                var start = null;
                if (data && data.averages)
                for(var i in data.averages)
                {
                    var vid = '#' + vote_id + data.averages[i].type;
                    var tot = '#' + tot_id  + data.averages[i].type;

                    $.fn.raty.start(data.averages[i].avg, vid);
                    $(tot).empty().append(data.averages[i].num + " votes")
                }
            }
        };
        $.ajax(cfg);
    });

    $('#layerslist').listview();
    $('<li>', {
            "data-role": "list-divider",
            text: "Base Layers"
        })
        .appendTo('#layerslist');
    var baseLayers = map.getLayersBy("isBaseLayer", true);
    $.each(baseLayers, function() {
        addLayerToList(this);
    });

    $('<li>', {
            "data-role": "list-divider",
            text: "Overlay Layers"
        })
        .appendTo('#layerslist');
    var overlayLayers = map.getLayersBy("isBaseLayer", false);
    $.each(overlayLayers, function() {
        addLayerToList(this);
    });
    $('#layerslist').listview('refresh');
    
    map.events.register("addlayer", this, function(e) {
        addLayerToList(e.layer);
    });
});

function addLayerToList(layer) {
    var item = $('<li>', {
            "data-icon": "check",
            "class": layer.visibility ? "checked" : ""
        })
        .append($('<a />', {
            text: layer.name
        })
            .click(function() {
                $.mobile.changePage('mappage');
                if (layer.isBaseLayer) {
                    layer.map.setBaseLayer(layer);
                } else {
                    layer.setVisibility(!layer.getVisibility());
                }
            })
        )
        .appendTo('#layerslist');
    layer.events.on({
        'visibilitychanged': function() {
            $(item).toggleClass('checked');
        }
    });
}
